/*
 * 版权所有 ( c ) 联想集团有限公司 2005-2009 保留所有权利。
 * 项目：	Lenovo Push Service
 * 文件名：	FileUtil.java
 * 版本:    1.0
 * 描述：	
 * 作者：	刘兵召
 * 日期：	2009-7-28 
 * 修改历史：
 * 【时间】		【修改者】	【修改内容】
 */
package com.feng.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 文件处理工具类
 * 
 * @author bing
 * @since 2008-12-14
 */
public class FileUtil {

	/**
	 * 行分隔符
	 */
	public final static String LINE_SEPARATOR = System.getProperty("line.separator");
	
	/**
	 * 格式化文件大小
	 * @param iappsize
	 * @return
	 */
	public static String getMkbSize(Long iappsize){
		Long rsK=new Double(java.lang.Math.ceil(iappsize/1024)).longValue();//KB 向上补1个kb
		DecimalFormat text=new DecimalFormat("#.00");//４舍五入
		Double rsM=new Double(text.format((rsK+0.0)/1024));//如果是M 可以是两位小数为Kb
		if(iappsize<1024){
			return "1KB";
		}else if(rsK<1024){
			return rsK+"KB";
		}else{
			return rsM+"M";
		}
	}

	/**
	 * 创建目录
	 * 
	 * @param file
	 * @return true/创建成功；false/创建失败；
	 */
	public static boolean createDirectory(File file) {
		if (file.exists()) {
			return true;
		}
		return file.mkdirs();
	}

	/**
	 * 创建目录
	 * 
	 * @param fileName
	 * @return true/创建成功；false/创建失败；
	 */
	public static boolean createDirectory(String dirName) {
		return createDirectory(new File(dirName));
	}

	/**
	 * 根据文件名读取文件
	 * 
	 * @param filename 文件路径
	 * @return
	 * @throws IOException
	 */
	public static String readFile2String(String filename) throws IOException {
		return readFile2String(new File(filename));
	}

	/**
	 * 从 File 对象中读取文件
	 * 
	 * @param file
	 *            传入的文件对象
	 * @return 文件内容（字符串）
	 * @throws IOException
	 */
	public static String readFile2String(File file) throws IOException {
		if ((file == null) || !file.exists() || file.isDirectory()) {
			return null;
		}
		return readInputStream2String(new FileInputStream(file));
	}

	/**
	 * 使用系统默认字符集读取二进制流
	 * 
	 * @param is
	 *            文件二进制输入流
	 * @return 文件内容（字符串）
	 * @throws IOException
	 */
	public static String readInputStream2String(InputStream is)
			throws IOException {
		return readInputStream2String(is, Charset.defaultCharset().name());
	}

	/**
	 * 使用指定编码读取二进制流
	 * 
	 * @param is
	 *            文件二进制输入流
	 * @param charset
	 *            读取文件使用编码
	 * @return 文件内容（字符串）
	 * @throws IOException
	 */
	public static String readInputStream2String(InputStream is, String charset)
			throws IOException {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			br = new BufferedReader(new InputStreamReader(is, charset));
			for (String str = null; (str = br.readLine()) != null;) {
				sb.append(str).append(LINE_SEPARATOR);
			}
		} finally {
			closeIO(br);
		}
		return sb.toString().trim();
	}

	public Properties getProperties(String file) throws IOException
    {
        String CONFIG_FILE_LOCATION;
        InputStream in;
        Properties props;
        CONFIG_FILE_LOCATION = file;
        in = null;
        props = null;
        System.out.println((new StringBuilder()).append("Reading ").append(CONFIG_FILE_LOCATION).toString());
        in = getResourceAsStream(CONFIG_FILE_LOCATION);
        props = new Properties();
        props.load(in);
        System.out.println((new StringBuilder()).append("Read ").append(CONFIG_FILE_LOCATION).append(" success").toString());
        if(in != null)
            try
            {
                in.close();
            }
            catch(FileNotFoundException ex)
            {
            	ex.printStackTrace();
            }
        if(in != null)
            try
            {
                in.close();
            }
            // Misplaced declaration of an exception variable
            catch(FileNotFoundException e)
            {
                System.out.println(new StringBuilder().append("Close ").append(CONFIG_FILE_LOCATION).append(" failed \uFF01").toString());
            } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        System.out.println(new StringBuilder().append("Read ").append(CONFIG_FILE_LOCATION).append(" failed \uFF01").toString());
        if(in != null)
            try
            {
                in.close();
            }
            // Misplaced declaration of an exception variable
            catch(FileNotFoundException e)
            {
                System.out.println(new StringBuilder().append("Close ").append(CONFIG_FILE_LOCATION).append(" failed \uFF01").toString());
            } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        if(in != null)
            try
            {
                in.close();
            }
            catch(Exception e)
            {
                System.out.println(new StringBuilder().append("Close ").append(CONFIG_FILE_LOCATION).append(" failed \uFF01").toString());
            }
        return props;
    }

	private InputStream getResourceAsStream(String config_file_location) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * --------------------------------------------------------------------------
	 * 
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static List<String> readFile2List(String filename)
			throws IOException {
		return readFile2List(new File(filename));
	}

	/**
	 * 将文件读取成为 List，List 中的每一个元素是文件中的一行字符串
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static List<String> readFile2List(File file) throws IOException {
		if ((file == null) || !file.exists() || file.isDirectory()) {
			return null;
		}
		BufferedReader br = null;
		List<String> list = new ArrayList<String>();
		try {
			br = new BufferedReader(new FileReader(file));
			for (String str = null; (str = br.readLine()) != null;) {
				list.add(str);
			}
		} finally {
			closeIO(br);
		}
		return list;
	}

	public static void writeString2File(String str, String filename)
			throws IOException {
		writeString2File(str, new File(filename));
	}

	public static void writeString2File(String str, File file)
			throws IOException {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(file));
			bw.write(str);
		} finally {
			closeIO(bw);
		}
	}

	public static void writeList2File(List<String> list, String filename)
			throws IOException {
		writeList2File(list, new File(filename), LINE_SEPARATOR);
	}

	public static void writeList2File(List<String> list, File file)
			throws IOException {
		writeList2File(list, file, LINE_SEPARATOR);
	}

	public static void writeList2File(List<String> list, String filename,
			String lineSeparator) throws IOException {
		writeList2File(list, new File(filename), lineSeparator);
	}

	/**
	 * 以 List 中的每一个元素作为写入文件中的一行
	 * 
	 * @param list
	 *            元素集
	 * @param file
	 *            文件
	 * @param lineSeparator
	 *            每个元素写入文件时的分隔符
	 * @throws IOException
	 */
	public static void writeList2File(List<String> list, File file,
			String lineSeparator) throws IOException {
		StringBuffer sb = new StringBuffer();
		for (int i = 0, k = list.size(); i < k; i++) {
			if (i > 0) {
				sb.append(lineSeparator);
			}
			sb.append(list.get(i));
		}
		writeString2File(sb.toString(), file);
	}

	/**
	 * 关闭 IO 流
	 * 
	 * @param io
	 * @throws IOException
	 */
	public static void closeIO(Closeable io) throws IOException {
		if (io != null) {
			io.close();
		}
	}

	public static void main(String[] args) {
		System.out.println(getMkbSize(10000000L));
	}
}
